﻿#region

using System;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI;
using CrazyTalk.Common;

#endregion

namespace CrazyTalk.Web.UI
{
    public class PageBase : Page, IHandler
    {
        public enum MessageType
        {
            /// <summary>
            ///     普通消息提示
            /// </summary>
            Alert,

            /// <summary>
            ///     成功信息
            /// </summary>
            Success,

            /// <summary>
            ///     错误信息
            /// </summary>
            Error,

            /// <summary>
            ///     询问消息
            /// </summary>
            Confirm,
        }

        /// <summary>
        ///     使用的换行符号，比如\n 或 <br />
        /// </summary>
        public const string LineBreakSymbol = "\n";

        /// <summary>
        ///     提示文字
        /// </summary>
        protected internal string MsgboxText = "";

        /// <summary>
        ///     当前页面检查到的错误数
        /// </summary>
        protected internal int PageErr = 0;

        /// <summary>
        ///     通过alert提示信息并进行跳转
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="url"></param>
        public void AlertAndGo(string msg, string url)
        {
            HttpContext current = HttpContext.Current;

            current.Response.Write(string.Format("<script>alert('{0}');location.href='{1}'</script>", msg, url));
            current.Response.End();
        }

        public new NameValueCollection Form()
        {
            return HttpContext.Current.Request.Form;
        }

        public new string Form(int index)
        {
            return Form()[index];
        }

        public new string Form(string key)
        {
            return Form()[key];
        }

        /// <summary>
        ///     获取指定位置的HttpContext.Current.Request.Form 的值并转换为对应数据类型
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public decimal FormToDecimal(int index)
        {
            return ConvertUtil.ToDecimal(Form()[index]);
        }

        /// <summary>
        ///     获取指定key的HttpContext.Current.Request.Form 的值并转换为对应数据类型
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public decimal FormToDecimal(string key)
        {
            return ConvertUtil.ToDecimal(Form()[key]);
        }

        public int FormToInt(int index)
        {
            return ConvertUtil.ToInt(Form()[index]);
        }

        public int FormToInt(string key)
        {
            return ConvertUtil.ToInt(Form()[key]);
        }

        public NameValueCollection Query()
        {
            return HttpContext.Current.Request.QueryString;
        }

        public string Query(int index)
        {
            return Query()[index];
        }

        public string Query(string key)
        {
            return Query()[key];
        }

        public decimal QueryToDecimal(int index)
        {
            return ConvertUtil.ToDecimal(Query()[index]);
        }

        public decimal QueryToDecimal(string key)
        {
            return ConvertUtil.ToDecimal(Query()[key]);
        }

        public int QueryToInt(int index)
        {
            return ConvertUtil.ToInt(Query()[index]);
        }

        public int QueryToInt(string key)
        {
            return ConvertUtil.ToInt(Query()[key]);
        }

        /// <summary>
        ///     增加错误提示
        /// </summary>
        /// <param name="errinfo">错误提示信息</param>
        public void AddErrLine(string errinfo)
        {
            if (MsgboxText.Length == 0)
            {
                MsgboxText = MsgboxText + errinfo;
            }
            else
            {
                MsgboxText = MsgboxText + "<br />" + errinfo;
            }
            PageErr++;
        }

        protected override void OnInit(EventArgs e)
        {
            if (Request.IsLocal == false)
            {
                Error += PageBase_Error;
            }
        }

        protected void PageBase_Error(object sender, EventArgs e)
        {
            try
            {
                //if (ConfigHelper.OpenError.ToLower() == "off") return;
                Exception exc = Server.GetLastError();
                if (exc == null)
                {
                    return;
                }
                StringBuilder sb = new StringBuilder();

                if (exc is SqlException && exc.Message.ToLower().IndexOf("fk_") != -1)
                {
                    sb.Append("<div class=\"mintitle\">您好！当前记录已经被引用，不能被删除。</div>");
                }
                else
                {
                    sb.Append("<div class=\"mintitle\">您好！您访问的页面出现的问题，请联系管理人员解决问题。</div>");
                }
            }
            catch
            {
            }
        }

        /// <summary>
        ///     通过前端跳转页面
        /// </summary>
        /// <param name="href">需要跳转到的页面地址</param>
        public virtual void RedirectJS(string href)
        {
            RunJavascript(string.Format("window.location.href='{0}'", href));
        }

        public virtual void Alert(string msg)
        {
            Page.ClientScript.RegisterStartupScript(GetType(), "tip", "alert('" + msg + "');", true);
        }

        public void MessageBox_On_The_Lower_Depths(string type, string message, string url, int showTime)
        {
            HttpContext.Current.Response.Write(string.Format(@"
<html><head>
<link href=""/Styles/mo/dialog.css"" rel=""stylesheet"" type=""text/css"" />
<script type=""text/javascript"" src=""/Scripts/jquery-1.7.1.js""></script>
<script type=""text/javascript"" src=""/Scripts/mo.ui.js""></script>
</head>
<body>
<script>
function nav() {{ window.top.location.href = '{2}'; }}
Message(""{0}"", '<div class=""s""></div><div class=""c"">{1}</div><div class=""e""></div>', {3}, {{ ""unique"": ""message"", ""center"": true }},nav);
</script>
</body></html>
", type, message, url, showTime));
        }

        /// <summary>
        ///     调用ymPrompt插件进行信息提示
        /// </summary>
        /// <param name="message">提示框信息内容</param>
        /// <param name="title">提示框标题，留空使用[提示]</param>
        /// <param name="msgType">提示框类型</param>
        /// <param name="url1">不需要进行网址跳转，可留空</param>
        /// <param name="url2">当有确定和取消两个选择时，当选择确定，则跳转到url1,否则跳转到url2</param>
        /// <param name="redirettPosition">跳转的位置，空值默认为当前页面，可以加上.parent，以在父级页面跳转</param>
        public void MessageBoxYM(string message, string title, MessageType msgType, string url1, string url2, string redirettPosition)
        {
            message = message.Replace("'", "’");
            string javascript = string.Empty;
            string handler = string.Empty;
            if (!string.IsNullOrEmpty(url1))
            {
                if (string.IsNullOrEmpty(url2))
                {
                    handler = string.Format("function handler(){{window{1}.location.href='{0}'}}", url1, redirettPosition);
                }
                else
                {
                    handler = string.Format("function handler(tp){{if(tp=='ok'){{window{2}.location.href='{0}'}}else{{window{2}.location.href='{1}'}}}}", url1, url2, redirettPosition);
                }
            }
            else
            {
                handler = "function handler(){}";
            }
            if (string.IsNullOrEmpty(title))
            {
                title = "提示";
            }
            switch (msgType)
            {
                case MessageType.Alert:
                    javascript = string.Format("{2}ymPrompt.alert('{0}',null,null,'{1}',handler);", message, title, handler);
                    break;
                case MessageType.Success:
                    javascript = string.Format("{2}ymPrompt.succeedInfo('{0}',null,null,'{1}',handler);", message, title, handler);
                    break;
                case MessageType.Error:
                    javascript = string.Format("{2}ymPrompt.errorInfo('{0}',null,null,'{1}',handler);", message, title, handler);
                    break;
                case MessageType.Confirm:
                    javascript = string.Format("{2}ymPrompt.confirmInfo('{0}',null,null,'{1}',handler);", message, title, handler);
                    break;
            }
            Page.ClientScript.RegisterStartupScript(GetType(), "messagebox", javascript, true);
        }

        /// <summary>
        ///     调用ymPrompt插件进行信息提示
        /// </summary>
        /// <param name="message">提示框信息内容</param>
        /// <param name="title">提示框标题，留空使用[提示]</param>
        /// <param name="msgType">提示框类型</param>
        /// <param name="url1">进行网址跳转</param>
        public void MessageBoxYM(string message, string title, MessageType msgType, string url1)
        {
            MessageBoxYM(message, title, msgType, url1, string.Empty, string.Empty);
        }

        /// <summary>
        ///     调用ymPrompt插件进行信息提示，并在父级页面进行跳转
        /// </summary>
        /// <param name="message">提示框信息内容</param>
        /// <param name="title">提示框标题，留空使用[提示]</param>
        /// <param name="msgType">提示框类型</param>
        /// <param name="url1">进行网址跳转</param>
        public void MessageBoxYM_Parent(string message, string title, MessageType msgType, string url1)
        {
            MessageBoxYM(message, title, msgType, url1, string.Empty, ".parent");
        }

        /// <summary>
        ///     调用ymPrompt插件进行信息提示
        /// </summary>
        /// <param name="message">提示框信息内容</param>
        /// <param name="title">提示框标题，留空使用[提示]</param>
        /// <param name="msgType">提示框类型</param>
        /// <param name="url1">不需要进行网址跳转，可留空</param>
        /// <param name="url2">当有确定和取消两个选择时，当选择确定，则跳转到url1,否则跳转到url2</param>
        public void MessageBoxYM(string message, string title, MessageType msgType, string url1, string url2)
        {
            MessageBoxYM(message, title, msgType, url1, url2, string.Empty);
        }

        /// <summary>
        ///     先进行格式化,再执行js
        /// </summary>
        /// <param name="javascriptFormat"></param>
        /// <param name="args"></param>
        public void RunJavascriptFormat(string javascriptFormat, params string[] args)
        {
            RunJavascript(string.Format(javascriptFormat, args), "common");
        }

        /// <summary>
        ///     执行js脚本
        /// </summary>
        /// <param name="javascript"></param>
        public void RunJavascript(string javascript)
        {
            RunJavascript(javascript, "common");
        }

        /// <summary>
        ///     执行js脚本
        /// </summary>
        /// <param name="javascript">脚本内容</param>
        /// <param name="key">要注册的启动的脚本的key</param>
        public void RunJavascript(string javascript, string key)
        {
            Page.ClientScript.RegisterStartupScript(GetType(), key, javascript, true);
        }

        public DateTime FormToDateTime(int index)
        {
            return ConvertUtil.ToDateTime(Form()[index]);
        }

        public DateTime FormToDateTime(string key)
        {
            return ConvertUtil.ToDateTime(Form()[key]);
        }

        public bool FormToBool(int index)
        {
            return ConvertUtil.ToBool(Form()[index]);
        }

        public bool FormToBool(string key)
        {
            return ConvertUtil.ToBool(Form()[key]);
        }

        public bool QueryToBool(int index)
        {
            return ConvertUtil.ToBool(Query()[index]);
        }

        public bool QueryToBool(string key)
        {
            return ConvertUtil.ToBool(Query()[key]);
        }

        public DateTime QueryToDateTime(int index)
        {
            return ConvertUtil.ToDateTime(Query()[index]);
        }

        public DateTime QueryToDateTime(string key)
        {
            return ConvertUtil.ToDateTime(Query()[key]);
        }
    }
}